<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
<script>
// class Light {
//   constructor() {
//     this.state = 'off';
//     this.button = null;
//   }
//   init() {
//     let btn = document.createElement('button');
//     btn.innerHTML = '开关';
//     this.button = document.body.appendChild(btn);
//     this.button.onclick = () => {
//       this.buttonWasPressed()
//     }
//   }
//   // buttonWasPressed() {
//   //   if(this.state === 'off') {
//   //     console.log('开灯');
//   //     this.state = 'on';
//   //   } else if(this.state === 'on') {
//   //     console.log('关灯');
//   //     this.state = 'off';
//   //   }
//   // }
//   buttonWasPressed() {
//     if(this.state === 'off') {
//       console.log('弱光');
//       this.state = 'weakLight';
//     } else if(this.state === 'weakLight') {
//       console.log('强光');
//       this.state = 'strongLight';
//     } else if(this.state === 'strongLight') {
//       console.log('关灯');
//       this.state = 'off';
//     }
//   }
// }
class SuperLightState {
  constructor(light) {
    this.light = light
  }
  buttonWasPressed() {
    throw new Error('父类的buttonWasPressed方法必须被重写')
  }
}
class OffLightState extends SuperLightState {
  constructor(light) {
    super(light)
  }
  buttonWasPressed() {
    console.log('弱光');
    this.light.setState(this.light.weakLightState)
  }
}
class WeakLightState extends SuperLightState {
  constructor(light) {
    super(light)
  }
  buttonWasPressed() {
    console.log('强光');
    this.light.setState(this.light.strongLightState)
  }
}
class StrongLightState extends SuperLightState {
  constructor(light) {
    super(light)
  }
  buttonWasPressed() {
    console.log('关灯');
    this.light.setState(this.light.offLightState)
  }
}
class Light {
  constructor() {
    this.offLightState = new OffLightState(this);
    this.weakLightState = new WeakLightState(this);
    this.strongLightState = new StrongLightState(this);
    this.button = null;
  }
  init() {
    let btn = document.createElement('button');
    btn.innerHTML = '开关';
    this.button = document.body.appendChild(btn);
    // 设置当前状态
    this.currState = this.offLightState;

    this.button.onclick = () => {
      this.currState.buttonWasPressed()
    }
  }
  setState(newState) {
    this.currState = newState;
  }
}
let light = new Light()
light.init()
</script>
</body>
</html>